var app = getApp();
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {},
    searchResult: {},
    containerShow: true,
    searchPanelShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(event) {
    var inTheatersUrl = app.globaData.doubanBase + "/top?type=Imdb&skip=0&limit=3&lang=Cn";
    var comingSoonUrl = app.globaData.doubanBase + "/top?type=Imdb&skip=0&limit=3&lang=Cn";
    var top250Url = app.globaData.doubanBase + "/top?type=Imdb&skip=0&limit=3&lang=Cn";
    this.getMovieListData(inTheatersUrl, "inTheaters", "正在热映");
    this.getMovieListData(comingSoonUrl, "comingSoon", "即将上映");
    this.getMovieListData(top250Url, "top250", "豆瓣TOP250");
  },
  // 跳转电影更多页面
  onMoreTap: function (event) {
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more-movie/more-movie?category=' + category,
    })
  },
  // 跳转电影详情页
  onMovieTap: function (event) {
    var movieId = event.currentTarget.dataset.movieid;
    console.log(movieId)
    wx.navigateTo({
      url: 'movie-detail/movie-detail?id=' + movieId,
    })
  },

  // 访问豆瓣API的公用方法
  getMovieListData: function (url, settedKey, categoryTitle) {
    var that = this;
    wx.request({
      url: url,
      header: {
        "Content-Type": ""
      },
      method: "GET",
      success: (res) => {
        that.processDoubanData(res.data, settedKey, categoryTitle);
      },
      fail: (err) => {}
    })
  },

  // 关闭搜索页
  onCancelImgTap: function (enent) {
    this.setData({
      containerShow: true,
      searchPanelShow: false,
      searchResult: {}
    })
  },
  // 搜索框焦点
  onBindFocus: function (event) {
    this.setData({
      containerShow: false,
      searchPanelShow: true
    })
  },

  onBindChange: function (event) {
    var text = event.detail.value;
    var searchUrl = "https://api.wmdb.tv/api/v1/movie/search?q=" + text;
    this.getMovieListData(searchUrl, "searchResult", "");
  },
  processDoubanData: function (moviesDouban, settedKey, categoryTitle) {
    var movies = [];
    for (var idx in moviesDouban) {
      var subject = moviesDouban[idx];
      for (var i in subject.data) {
        var data = subject.data[i];
        var name = data.name;
        if (name.length > 6) {
          name = name.substring(0, 6) + "...";
        }
        var temp = {
          title: name,
          movieId: subject.doubanId,
          coverageUrl: data.poster,
          average: subject.imdbRating,
          stars: util.convertToStarsArray(subject.rottenVotes)
        }
        movies.push(temp);
      }
      var readyData = {};
      readyData[settedKey] = {
        categoryTitle: categoryTitle,
        movies: movies
      };
    }
    this.setData(readyData)
  }
})